﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.Model.ViewModel.BaseData;

namespace ZBJF.Warranty.BLL
{
    public partial class D_CityService
    {
        public D_City LoadByID(int cityId)
        {
            return LoadEntities(c => c.CityID == cityId).FirstOrDefault();
        }
        public IQueryable<D_City> GetCityAll()
        {
            return LoadEntities(o => true);
        }

        public IQueryable<D_City> GetCityListByProvinceID(int provinceID)
        {
            var expressionWhere = PredicateExtensions.True<D_City>();
            expressionWhere = expressionWhere.And(o => o.ProvinceID == provinceID);
            return LoadEntities(expressionWhere);
        }
        public bool IsExist(int provinceId, string cityName, int id = 0)
        {
            var expressionWhere = PredicateExtensions.True<D_City>();
            if (!string.IsNullOrWhiteSpace(cityName))
                expressionWhere = expressionWhere.And(o => o.CityName.Equals(cityName) && o.ProvinceID == provinceId);
            if (id != 0)
                expressionWhere = expressionWhere.And(o => o.CityID != id);
            return LoadEntities(expressionWhere).Any();
        }

        public IQueryable<D_City> GetPagingList(D_CityModel model, out int total)
        {
            var expressionWhere = PredicateExtensions.True<D_City>();
            if (!string.IsNullOrEmpty(model.Keyword))
            {
                string kw = model.Keyword.ToLower();
                expressionWhere = expressionWhere.And(o => o.CityName.ToLower().Contains(kw));
            }
            if (!string.IsNullOrEmpty(model.ProvinceIds))
            {
                var expressright =
                                PredicateExtensions.False<D_City>();
                var arr = model.ProvinceIds.Split(',');
                foreach (var item in arr)
                {
                    if (string.IsNullOrEmpty(item)) continue;
                    var brandId = 0;
                    if (int.TryParse(item, out brandId))
                    {
                        expressright = expressright.Or(c => c.ProvinceID == brandId);
                    }
                }
                expressionWhere = expressionWhere.And(expressright);
            }
            if (model.ProvinceID.HasValue)
            {
                expressionWhere = expressionWhere.And(o => o.ProvinceID == model.ProvinceID);
            }
            if (string.IsNullOrWhiteSpace(model.iSorts))
            {
                model.iSorts = "Sort asc";
            }
            return LoadPagerEntities<D_City>(model.PageIndex, model.iDisplayLength, out total, expressionWhere, model.iSorts);
        }
    }
}
